package com.bizmda.bizsip.source.api;

import lombok.Getter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shizhengye
 */
@Getter
public class AppServiceClientProxy<T> implements InvocationHandler {

    private final Class<T> mapperInterface;
    private final Map<Method, AppServiceClientMethod> methodCache;
    private final String bizServiceId;

    public AppServiceClientProxy(Class<T> mapperInterface, String bizServiceId) {
        this.mapperInterface = mapperInterface;
        this.methodCache = new HashMap<>();
        this.bizServiceId = bizServiceId;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        final AppServiceClientMethod serviceClientMethod = cachedMapperMethod(method);

        return serviceClientMethod.execute(args);
    }

    private AppServiceClientMethod cachedMapperMethod(Method method) {
        return this.methodCache.computeIfAbsent(method,
                key -> new AppServiceClientMethod(key, this));
    }

}
